package com.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.demo.constant.Constant;
import com.demo.entity.PrintTemplate;
import com.demo.mapper.PrintTemplateMapper;
import com.demo.response.Result;
import com.demo.service.IPrintTemplateService;
import com.demo.util.TimeUtil;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 文书模板 服务实现类
 * @author zm
 * @since 2020-11-24
 */
@Service
public class PrintTemplateServiceImpl extends ServiceImpl<PrintTemplateMapper, PrintTemplate> implements IPrintTemplateService {
    @Resource
    PrintTemplateMapper templateMapper;

    /**
     * 编辑文书模板
     * @param printTemplate   实体对象
     * @return
     */
    @Override
    public Result updatePrintTemplate(PrintTemplate printTemplate) {
        if (printTemplate.getTemplateId() == null || printTemplate.getUpdatedUserId() == null){
            return Result.error(Constant.KEY_ID);
        }
        boolean flag = this.updateById(printTemplate);
        if (flag == false){return Result.error(Constant.DB_ERROR);}
        return Result.success();
    }

    /**
     * 查询文书模板
     * @param pageNumber        页码
     * @param pageSize          每页数量
     * @param templateId        模板ID
     * @param templateType      模板类型
     * @param templateName      模板名称
     * @return
     */
    @Override
    public Result printTemplateList(Integer pageNumber, Integer pageSize, Integer templateId, Integer templateType, String templateName) {
        IPage<PrintTemplate> page = new Page<>(pageNumber,pageSize);
        QueryWrapper<PrintTemplate> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(templateId != null,"template_id",templateId);
        queryWrapper.eq(templateType != null,"template_type",templateType);
        queryWrapper.like(TimeUtil.isString(templateName),"template_name",templateName);
        queryWrapper.isNull("deleted_user_id");
        queryWrapper.orderByDesc("template_id");
        queryWrapper.select("template_id","user_id","template_name","template_type","template_content");
        page = templateMapper.selectPage(page,queryWrapper);
        PageInfo<PrintTemplate> pageInfo = new PageInfo<>(page.getRecords());
        pageInfo.setPages((int) page.getPages());
        pageInfo.setTotal(page.getTotal());
        if (pageNumber.equals(page.getPages())){
            pageInfo.setIsLastPage(false);
        }else {pageInfo.setIsLastPage(true);}
        return Result.success(pageInfo);
    }


}
